﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using BLL.Security;
using BLL.Services;
using BLL.Services.Responses;
using Web.Infrastructure;
using Web.Infrastructure.Models;
using Web.Models.Responses;

namespace Web.Controllers
{
    /// <summary>
    /// The comments controller.
    /// </summary>
    public partial class ResponsesController : FrontendController
    {
        private readonly IResponsesService _responsesService;

        private readonly IEnvironmentContext _environmentContext;

        public ResponsesController(
            IResponsesService responsesService,
            IEnvironmentContext environmentContext)
        {
            _responsesService = responsesService;
            _environmentContext = environmentContext;
        }

        public virtual ActionResult Save(ResponseModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Errors = GetErrors;
                return Json(model);
            }
            var comment = (Response) model;
            comment.UserId = _environmentContext.User.UserId;
            comment.DateOfPublish = DateTime.Now;
            try
            {
                _responsesService.Create(comment);
                model.SuccessMessage = @"Ваш отзыв добавлен!";
                return Json(model);
            }
            catch (ServiceException exception)
            {
                model.Errors = new List<ErrorModel> { new ErrorModel(exception.ToString()) };
                return Json(model);
            }
        }

        public virtual ActionResult Show(int bookId)
        {
            return Json(new BookResponsesModel(_responsesService.GetResponseByBook(bookId)), JsonRequestBehavior.AllowGet);
        }

        public virtual ActionResult Template()
        {
            return PartialView(MVC.Responses.Views.Template);
        }
    }
}
